package com.project.everywheretakeaway;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;

public class RestaurantProvider extends ContentProvider {

	public static final Uri CONTENT_URI = Uri.parse("content://com.project.restaurantprovider/restaurants");
	public static final String MAP_PREFS = "MAP_PREF";
	
	// Questi devono essere settabili dalle preferenze (almeno l'IP)
	private static final String SOAP_ACTION = "http://ws.business.everywheretakeaway.org/findAvailableRestaurants";
    private static final String METHOD_NAME = "findAvailableRestaurants";
    private static final String NAMESPACE = "http://ws.business.everywheretakeaway.org/";
    //private static final String URL = "http://192.168.1.100:8080/EverywhereTakeawayWS/EverywhereTakeawayWS?WSDL";
    private static final String PARTIAL_URL = "EverywhereTakeawayWS/EverywhereTakeawayWS?WSDL";
	
	//URI MATCHER
	private static final int RESTAURANTS = 1;
	private static final int RESTAURANTS_CATEGORY = 2;
	
	private static final UriMatcher uriMatcher;
	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI("com.project.restaurantprovider", "restaurants", RESTAURANTS);
		uriMatcher.addURI("com.project.restaurantprovider", "restaurants/#", RESTAURANTS_CATEGORY);
	}
	
	private static final String TAG = "RESTAURANTS";
	
	
	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		return true;
	}
	
	
	
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		switch(uriMatcher.match(uri)) {
		
		case RESTAURANTS:
			return "vnd.android.cursor.dir/vnd.project.everywheretakeaway";
			
		case RESTAURANTS_CATEGORY:
			return "vnd.android.cursor.dir/vnd.project.everywheretakeaway";
			
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		
	}
}

	@Override
	public Uri insert(Uri arg0, ContentValues arg1) {
		// TODO Auto-generated method stub
		return null;
	}

	

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) {
		
		// Momentaneamente creo un cursore con dati statici per provare
		Context context = getContext();
		SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		//SharedPreferences mySharedPreferences = getContext().getSharedPreferences(MAP_PREFS,Activity.MODE_PRIVATE);
		MatrixCursor cursor = new MatrixCursor(new String[] {"_id","name","phone","street","city", "lat", "long"});
		
		String URL = "http://" + mySharedPreferences.getString("PREF_IP_ADDRESS", "localhost") + ":" + mySharedPreferences.getString("PREF_PORT", "8080") + "/" + PARTIAL_URL;
		
		String id;
		String name;
		String phone;
		String street;
		String city;
		String latitude;
		String longitude;

		
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		
		// QUESTI VANNO POI PRESI DAL GPS
		request.addProperty("latitude", mySharedPreferences.getString("device_lat", "0"));
		request.addProperty("longitude", mySharedPreferences.getString("device_lng", "0"));
		
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
         
        envelope.setOutputSoapObject(request);
 
        HttpTransportSE ht = new HttpTransportSE(URL);
        
        try {
        	
        	ht.call(SOAP_ACTION, envelope);
        	
        	//SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
        	Vector response = (Vector)envelope.getResponse();
      
        	
        	for(int i=0;i<response.size();i+=7) {
        		
        		id = ((SoapPrimitive)response.get(i)).toString();
        		name = ((SoapPrimitive)response.get(i+1)).toString();
        		phone = ((SoapPrimitive)response.get(i+2)).toString();
        		street = ((SoapPrimitive)response.get(i+3)).toString();
        		city = ((SoapPrimitive)response.get(i+4)).toString();
        		latitude = ((SoapPrimitive)response.get(i+5)).toString();
        		longitude = ((SoapPrimitive)response.get(i+6)).toString();
        		
        		cursor.addRow(new Object[] {id,name,phone,street,city,latitude,longitude});
        		
        	}

        	
        	
        } catch (Exception e) {
            // DECOMMENT FOR DEBUG!!
        	//throw new IllegalArgumentException(e.toString());
        	
        	// Inserisco dei risultati finti per testare l'applicazione quando non ho il web service su
			cursor.addRow(new Object[] {"1","Boot Hill", "0111111", "Via cavour 5", "bra", "44.693019", "7.857346"});
			
			// STRADA ORTI 44.693019,7.857346
			// VIA MARCONI 44.697625,7.851123
			
			
			switch(uriMatcher.match(uri)) {
			
				case RESTAURANTS:
					cursor.addRow(new Object[] {"2","Open", "0121111", "Via roma 5", "torino", "44.697625", "7.851123"});
					break;		
					
				default:
					break;
			
			}
        	
        }
		
			
		// Register the contexts ContentResolver to be notified if the cursor result set changes.
		cursor.setNotificationUri(getContext().getContentResolver(), uri);	

		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues arg1, String arg2, String[] arg3) {
		getContext().getContentResolver().notifyChange(uri, null);
		return 1;
	}

}
